package me.numark.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import me.numark.fragments.AskLoginFragment;
import me.numark.model.Feed;
import me.numark.model.FeedTag;
import me.numark.model.LabelsListResponse;
import me.numark.view.checktagview.TagListView;
import me.numark.view.tagview.OnTagClickListener;
import me.numark.view.tagview.OnTagDeleteListener;
import me.numark.view.tagview.Tag;
import me.numark.view.tagview.TagView;
import me.numark.R;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Utils;

public class PublishActivity extends BaseActivity implements View.OnClickListener
        //, TextView.OnEditorActionListener
        {
    @Bind(R.id.news_title)
    EditText newsTitle;

    /*@Bind(R.id.text_num)
    TextView inputNum;*/

    @Bind(R.id.publish_tagview)
    TagListView publishTagView;

    @Bind(R.id.local_tagview)
    TagListView localTagView;

    @Bind(R.id.input_edit_a)
    EditText editText;

    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.right_button)
    Button rightButton;
    @Bind(R.id.input_btn)
    Button inputButton;
    @Bind(R.id.scroll_view)
    ScrollView scrollView;
    String url;
    String title;
    String[] str = new String[]{"asasaas","hehehe","xixixix"};
    List<FeedTag> localList = new ArrayList<>();
    List<Feed> publishList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_publish;
        super.onCreate(savedInstanceState);
        title = getIntent().getStringExtra(WebviewActivity.EXTRA_TITLE);
        url = getIntent().getStringExtra(Constants.EXTRA_URL);
        publishTagView.fromType = 3;
        localTagView.fromType = 3;
        if (TextUtils.isEmpty(url)){
            Toast.makeText(this,"获取地址失败",Toast.LENGTH_SHORT);
            finish();
        }
        if (!TextUtils.isEmpty(title)){
            newsTitle.setText(title);
        }
        titleTextView.setText(R.string.recommend);
        //rightImage.setImageResource(R.drawable.action_bar_publish);
        //rightImage.setVisibility(View.VISIBLE);
        //rightImage.setOnClickListener(this);
        rightButton.setVisibility(View.VISIBLE);
        rightButton.setOnClickListener(this);
        //editText.setOnEditorActionListener(this);
        /*editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = editText.getText().toString().length();
                if (number > 80){
                    inputNum.setTextColor(Color.parseColor("#ff0000"));
                }else{
                    inputNum.setTextColor(Color.parseColor("#999999"));
                }
                inputNum.setText("" + number);
            }
        });*/
        inputButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Global.isLoggedIn()) {
                    AskLoginFragment.show(PublishActivity.this);

                } else {
                    String string = null;
                    if (editText.getText().toString() != null && !editText.getText().toString().equals("")) {
                        string = editText.getText().toString();
                        if (string.length() > 80) {
                            Utils.showSnackbar(rootView, R.string.text_num_is_too_more);
                            return;
                        }
                        FeedTag feedTag = new FeedTag();
                        feedTag.self_like = true;
                        feedTag.content = string;
                        publishTagView.addTag(feedTag, true);
                        editText.setText("");
                        // 隐藏输入法
                        InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
// 显示或者隐藏输入法
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                            }
                        }, 500);
                    }
                }
            }
        });


        new RequestServerTask<LabelsListResponse>(LabelsListResponse.class) {
            @Override
            protected String requestServer() {
                return HttpUtil.get(NetworkConstants.GET_RECOMMEND_LABELS, null);
            }

            @Override
            protected void onSuccess(LabelsListResponse result) {
                if (result.data!=null){
                    if (result.data.size()>0){
                        for (int i = 0; i < result.data.size(); i++) {
                            FeedTag feedTag = new FeedTag();
                            String s = result.data.get(i);
                            feedTag.self_like = false;
                            feedTag.content = s;
                            localTagView.addTag(feedTag);
                            localList.add(feedTag);
                        }
                    }
                }
            }
        }.setSnackbarView(rootView).start();

       /* localTagView.setOnTagClickListener(new OnTagClickListener() {
            @Override
            public void onTagClick(Tag tag, int position) {

                tag.layoutColor = Color.parseColor("#00b16a");
                tag.tagTextColor = Color.parseColor("#ffffff");
                tagView.addTag(tag);
                //scrollView.fullScroll(View.FOCUS_DOWN);
                localTagView.remove(position);
            }
        });
        tagView.setOnTagClickListener(new OnTagClickListener() {

            @Override
            public void onTagClick(Tag tag, int position) {
                tag.isDeletable = false;
                tag.layoutColor = Color.parseColor("#ffffff");
                tag.tagTextColor = Color.parseColor("#00b16a");
                localTagView.addTag(tag);
                tagView.remove(position);
            }
        });*/
        localTagView.setOnTagClickListener(new TagListView.OnTagClickListener() {
            @Override
            public void onTagClick(me.numark.view.checktagview.TagView tagView, FeedTag tag) {
                tag.self_like = true;
                publishTagView.addTag(tag,true);
                localTagView.removeTag(tag);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                }, 300);

            }
        });

        publishTagView.setOnTagClickListener(new TagListView.OnTagClickListener() {
            @Override
            public void onTagClick(me.numark.view.checktagview.TagView tagView, FeedTag tag) {
                tag.self_like = false;

                localTagView.addTag(tag,true);
                publishTagView.removeTag(tag);
            }
        });
    }
    private Handler handler = new Handler();
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.right_button:
                if (!TextUtils.isEmpty(url)) {
                    publish();
                }
                break;
        }
    }

    /**
     * 发布方法
     */
    void publish() {

        final String title = newsTitle.getText().toString().trim();
        if (title.length() == 0) {
            Utils.showSnackbar(rootView, R.string.mark_title_empty);
            return;
        }
        List<FeedTag> tags = publishTagView.getTags();
        Set<String> set= new HashSet<>();
        for (int i=0;i<tags.size();i++){
            set.add(tags.get(i).content);
        }
        final String json = new Gson().toJson(set);
        new RequestServerTask<BaseResponse>(BaseResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<>();
                params.put("url",url);
                params.put("title", title);
                params.put("labels", json);
                return HttpUtil.post(String.format(NetworkConstants.PUBLISH_MARK, Global.getCurrentUid()), params);

            }

            @Override
            protected void onSuccess(BaseResponse result) {
                LocalBroadcastManager.getInstance(getBaseContext())
                        .sendBroadcast(new Intent(Constants.ACTION_USER_CHANGED));
                finish();
                Utils.showToast(R.string.recommend_success);
            }
        }.setSnackbarView(rootView).start();

    }


    /*@Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE||(event!=null && event.getKeyCode()==KeyEvent.KEYCODE_ENTER)) {
            if (!Global.isLoggedIn()) {
                AskLoginFragment.show(this);

            }else {
                String string =null;
                if (editText.getText().toString()!=null&&!editText.getText().toString().equals("")) {
                    string = editText.getText().toString();
                    if (string.length()>80){
                        Utils.showSnackbar(rootView,R.string.text_num_is_too_more);
                        return false;
                    }
                    FeedTag feedTag = new FeedTag();
                    feedTag.self_like = true;
                    feedTag.content = string;
                    publishTagView.addTag(feedTag,true);
                    editText.setText("");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    },500);
                }
                return true;
            }

        }
        return false;
    }*/
}
